package cn.edu.tsc.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.tsc.dao.UserDao;
import cn.edu.tsc.pojo.User;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public LoginServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收数据
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        String req_code = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);

        boolean flag = false;
        User user = null;

        if (req_code != null && req_code.equalsIgnoreCase(code)) {
            user = new User(name, password);
            //调用dao
            UserDao userDao = new UserDao();
            flag = userDao.selectUser(user);

        }

        //分发网页
        if (flag) {

//            request.setAttribute("user",user);
            HttpSession session = request.getSession();
            session.setAttribute("user", user);

            request.getRequestDispatcher("/FindAllServlet").forward(request, response);
        } else
            response.sendRedirect("/error.jsp");
    }

}
